package net.organizer.ui.actionhandler;

import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import net.organizer.dao.Domain;
import net.organizer.dao.OrgPerson;

import org.json.JSONObject;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class OrgPersonDeleteActionHandler extends ActionHandlerBase {
	private static final Logger logger = Logger.getLogger(OrgPersonDeleteActionHandler.class.getName());

	@Override
	public void handleAction(HttpServletRequest req, JSONObject respJSONObject) throws Exception {
		logger.fine("handleAction");
		Domain domain = new Domain();
		domain.setName("domain1");
		List<Key<OrgPerson>> keys = new LinkedList<Key<OrgPerson>>();
		Objectify ofy = ObjectifyService.beginTransaction();
		try {
			if (req.getParameterValues("id") != null) {
				for (String value : req.getParameterValues("id")) {
					logger.finer(String.format("...parameter value: %s", value));
					Long id = Long.parseLong(value);
					keys.add(OrgPerson.getKey(domain, id));
				}
				logger.info(String.format("after load of http params... ids.size(): %d", keys.size()));
			}else{
				throw new RuntimeException("attempt to delete, but not ids were provided");
			}
			ofy.delete(keys);
			ofy.getTxn().commit();
		} finally {
			if (ofy.getTxn().isActive()) {
				ofy.getTxn().rollback();
			}
		}
	}
}
